﻿using System;
using System.Threading;

using DreamCube.WebServer.WinServiceModel;
using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.WebServer.WinService
{
    /// <summary>
    /// 守护进程的基类
    /// </summary>
    internal abstract class KeepLiveServer
    {
        /// <summary>
        /// 定时器
        /// </summary>
        protected Timer timer = null;

        public void Start()
        {
            try
            {
                if (timer == null)
                {
                    timer = new Timer(new TimerCallback((o) =>
                    {
                        try
                        {
                            //检查服务器进程的存活
                            DoCheckServer();
                        }
                        catch (Exception)
                        {
                        }
                        finally
                        {
                            timer.Change(5000, Timeout.Infinite);
                        }
                    }), null, 5000, Timeout.Infinite);
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 检查服务器
        /// </summary>
        public abstract void DoCheckServer();

        /// <summary>
        /// 停止服务触发的事件
        /// </summary>
        public void Stop()
        {
            try
            {
                if (timer != null)
                    timer.Dispose();
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }
    }
}
